package com.hxci.pointmap.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hxci.pointmap.dao.LoginDAO;
import com.hxci.pointmap.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {

    private LoginDAO loginDAO = new LoginDAO();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求编码
        req.setCharacterEncoding("UTF-8");

        // 设置响应编码和内容类型
        resp.setContentType("application/json;charset=UTF-8");

        // 获取操作类型
        String actionType = req.getParameter("actionType");

        // 创建响应对象
        Map<String, Object> responseMap = new HashMap<>();

        try {
            if ("getCurrentUser".equals(actionType)) {
                // 获取当前用户信息
                HttpSession session = req.getSession(false);
                if (session != null) {
                    Integer userId = (Integer) session.getAttribute("userId");
                    if (userId != null) {
                        User user = loginDAO.getUserById(userId);
                        if (user != null) {
                            // 不返回密码信息
                            user.setLoginPwd(null);

                            responseMap.put("success", true);
                            responseMap.put("user", user);
                        } else {
                            responseMap.put("success", false);
                            responseMap.put("message", "用户不存在");
                        }
                    } else {
                        responseMap.put("success", false);
                        responseMap.put("message", "用户未登录");
                    }
                } else {
                    responseMap.put("success", false);
                    responseMap.put("message", "会话已过期");
                }
            } else if ("updateProfile".equals(actionType)) {
                // 更新用户信息
                HttpSession session = req.getSession(false);
                if (session != null) {
                    Integer userId = (Integer) session.getAttribute("userId");
                    if (userId != null) {
                        User user = loginDAO.getUserById(userId);
                        if (user != null) {
                            // 获取表单参数
                            String userName = req.getParameter("userName");
                            String oldPassword = req.getParameter("oldPassword");
                            String newPassword = req.getParameter("newPassword");

                            // 更新姓名
                            if (userName != null && !userName.trim().isEmpty()) {
                                user.setUserName(userName.trim());
                            }

                            // 如果提供了新密码，需要验证旧密码
                            if (newPassword != null && !newPassword.trim().isEmpty()) {
                                if (oldPassword == null || oldPassword.trim().isEmpty()) {
                                    responseMap.put("success", false);
                                    responseMap.put("message", "修改密码需要提供当前密码");

                                    // 输出JSON响应
                                    outputJsonResponse(resp, responseMap);
                                    return;
                                }

                                // 验证旧密码
                                if (!oldPassword.equals(user.getLoginPwd())) {
                                    responseMap.put("success", false);
                                    responseMap.put("message", "当前密码不正确");

                                    // 输出JSON响应
                                    outputJsonResponse(resp, responseMap);
                                    return;
                                }

                                // 更新密码
                                user.setLoginPwd(newPassword.trim());
                            }

                            // 更新数据库
                            int result = loginDAO.updateUser(user);
                            if (result > 0) {
                                // 如果更新了密码，更新session中的密码
                                if (newPassword != null && !newPassword.trim().isEmpty()) {
                                    // 用户需要重新登录
                                    session.invalidate();
                                    responseMap.put("needReLogin", true);
                                    responseMap.put("message", "密码已修改，请重新登录");
                                } else {
                                    responseMap.put("message", "个人信息更新成功");
                                }

                                responseMap.put("success", true);
                            } else {
                                responseMap.put("success", false);
                                responseMap.put("message", "更新失败，请稍后再试");
                            }
                        } else {
                            responseMap.put("success", false);
                            responseMap.put("message", "用户不存在");
                        }
                    } else {
                        responseMap.put("success", false);
                        responseMap.put("message", "用户未登录");
                    }
                } else {
                    responseMap.put("success", false);
                    responseMap.put("message", "会话已过期");
                }
            } else if ("register".equals(actionType)) {
                // 处理用户注册
                String loginAccount = req.getParameter("loginAccount");
                String loginPwd = req.getParameter("loginPwd");
                String userName = req.getParameter("userName");
                String captcha = req.getParameter("captcha");
                
                // 验证验证码
                String sessionCaptcha = (String) req.getSession().getAttribute("captcha");
                if (sessionCaptcha == null || !sessionCaptcha.equalsIgnoreCase(captcha)) {
                    responseMap.put("success", false);
                    responseMap.put("message", "验证码错误");
                } else {
                    // 检查用户名是否已存在
                    User existingUser = loginDAO.getUserByLoginAccount(loginAccount);
                    if (existingUser != null) {
                        responseMap.put("success", false);
                        responseMap.put("message", "用户名已存在");
                    } else {
                        // 创建新用户
                        User newUser = new User();
                        newUser.setLoginAccount(loginAccount);
                        newUser.setLoginPwd(loginPwd);
                        // 设置用户姓名默认为"普通用户"
                        newUser.setUserName("普通用户");
                        
                        // 添加用户到数据库
                        int result = loginDAO.addUser(newUser);
                        if (result > 0) {
                            responseMap.put("success", true);
                            responseMap.put("message", "注册成功！请登录");
                        } else {
                            responseMap.put("success", false);
                            responseMap.put("message", "注册失败，请稍后再试");
                        }
                    }
                }
            } else if ("list".equals(actionType)) {
                // 获取用户列表
                List<User> userList = loginDAO.getAllUsers();
                req.setAttribute("userList", userList);
                req.getRequestDispatcher("user_list.jsp").forward(req, resp);
                return; // 不再输出JSON，直接转发
            } else if ("getUserById".equals(actionType)) {
                // 根据ID获取用户信息
                String userId = req.getParameter("id");
                if (userId != null && !userId.isEmpty()) {
                    try {
                        User user = loginDAO.getUserById(Integer.parseInt(userId));
                        if (user != null) {
                            // 不返回密码信息
                            user.setLoginPwd(null);
                            responseMap.put("success", true);
                            responseMap.put("user", user);
                        } else {
                            responseMap.put("success", false);
                            responseMap.put("message", "用户不存在");
                        }
                    } catch (NumberFormatException e) {
                        responseMap.put("success", false);
                        responseMap.put("message", "无效的用户ID");
                    }
                } else {
                    responseMap.put("success", false);
                    responseMap.put("message", "用户ID不能为空");
                }
            } else if ("deleteUser".equals(actionType)) {
                // 删除用户
                String userId = req.getParameter("id");
                if (userId != null && !userId.isEmpty()) {
                    try {
                        int id = Integer.parseInt(userId);
                        // 获取当前登录用户ID
                        HttpSession session = req.getSession(false);
                        Integer currentUserId = (Integer) session.getAttribute("userId");
                        
                        // 不能删除自己
                        if (currentUserId != null && currentUserId.equals(id)) {
                            responseMap.put("success", false);
                            responseMap.put("message", "不能删除当前登录用户");
                        } else {
                            int result = loginDAO.deleteUser(id);
                            if (result > 0) {
                                responseMap.put("success", true);
                                responseMap.put("message", "用户删除成功");
                            } else {
                                responseMap.put("success", false);
                                responseMap.put("message", "删除失败，用户不存在");
                            }
                        }
                    } catch (NumberFormatException e) {
                        responseMap.put("success", false);
                        responseMap.put("message", "无效的用户ID");
                    }
                } else {
                    responseMap.put("success", false);
                    responseMap.put("message", "用户ID不能为空");
                }
            } else {
                responseMap.put("success", false);
                responseMap.put("message", "未知操作类型");
            }
        } catch (Exception e) {
            e.printStackTrace();
            responseMap.put("success", false);
            responseMap.put("message", "系统错误：" + e.getMessage());
        }

        // 输出JSON响应
        outputJsonResponse(resp, responseMap);
    }

    private void outputJsonResponse(HttpServletResponse resp, Map<String, Object> responseMap) throws IOException {
        // 将响应对象转换为JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonResponse = objectMapper.writeValueAsString(responseMap);

        // 输出JSON响应
        PrintWriter out = resp.getWriter();
        out.print(jsonResponse);
        out.flush();
    }
}
